<script setup lang="ts">
import { ref } from "vue";
import { useSSE } from "@/service/eventSource";
import { useMdStream } from "@/utils/useMdStream";

const { html, append, reset } = useMdStream();

const content = ref("");

// const getToken = () => {
//   return "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJjaGF0X2JpIiwic3ViIjoiIiwiYXVkIjoiIiwiZXhwIjoxNzU5MzAwNjg3LCJpYXQiOjE3NTg4Njg2ODcsImp0aSI6IiIsIm5iZiI6MCwidXNlcl9pZCI6IjY4M2VhM2VlOTgwMTBlODk0YmI3YjdmNiIsInVzZXJuYW1lIjoiYWRtaW4iLCJwaG9uZSI6IjEzMzMzMzMzMzMzIn0.gjWz41D830Cqhim9H0YHo3323ewlbbUnV9l5K-l2am0";
// };

const data = ref({
  user_id: "123456",
  query: "北京7日游，有什么好推荐的吗？",
  web_search: false,
  thinking: false,
});

const { start, abort, isClosed } = useSSE({
  url: "/zc-api/chat/68d65184967108327fdbfcb0/stream",
  method: "POST",
  //   headers: { Authorization: `Bearer ${getToken()}` },
  body: data.value,
  onOpen() {
    console.log("连接成功");
    reset();
  },
  onMessage(chunk) {
    // 后端一次推一个 delta
    console.log(chunk);
    const { content = "" } = chunk;
    // content.value += message;
    append(content);
  },
  onError(err) {
    if (err.name !== "AbortError") {
      console.error("[SSE] 业务错误", err);
    }
  },
  onClose() {
    console.log("会话结束");
  },
});

// 发送
const send = () => {
  content.value = "";
  start();
};

// 用户点击“停止生成”
const stop = () => abort();
</script>

<template>
  <button @click="send">提问</button>
  <button v-if="!isClosed" @click="stop">停止生成</button>
  <!-- 实时渲染区 -->
  <div id="md-container" class="prose" v-html="html"></div>
</template>

<style lang="less" module>
/* 高亮主题（任选） */
@import "highlight.js/styles/github.css";
#md-container {
  max-height: 60vh;
  overflow: auto;
  border: 1px solid #eee;
  padding: 12px;
}
</style>
